// pages/index/shop/index.js
const app = getApp(); // 获取应用实例

Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '',
    showCode: '12345',
    visitNum: 0,
    useNum: 0,
    // 基本信息
    shopid: 0,
    shopName: '木桶饭',
    desc: '稻花香大米，农家土鸡',
    bgimg: '/imgs/bai.png',
    headimg: '/imgs/bai.png',
    adimg: '/imgs/bai.png',
    // 分类信息
    cateTotal: 0,
    catelist: [
    //   {id: 1, title: '卤味'},
    //   {id: 2, title: '小炒肉'},
    ],
    // 商品信息
    gTotal: 0,
    glist: [
    //   {id: 1, title: '苹果10', price: 5000},
    //   {id: 2, title: '苹果12', price: 12000},
    ],
    // 订单信息
    orderTotal: 0,
    orderlist: [
    //   {
    //     id: 1, orderno: '123123', title: '11111', 
    //     num: 11, money: 100,
    //   },
    //   {
    //     id: 2, orderno: '456456', title: '22222', 
    //     num: 22, money: 150,
    //   },
    ],
    // 评论
    commentTotal: 0,
    commentlist: [
    //   {
    //     id: 1, nickname: '张三', typeName: '门店',
    //     cnt: '11111', addtime: '2024-05-06'
    //   },
    //   {
    //     id: 2, nickname: '李四', typeName: '门店',
    //     cnt: '11111', addtime: '2024-05-06'
    //   },
    ],
    // 关注
    followTotal: 0,
    followlist: [
    //   {
    //     id: 1, nickname: '11111', 
    //     typeName: '商品', addtime: '2024-05-06',
    //   },
    //   {
    //     id: 2, nickname: '22222', 
    //     typeName: '商品', addtime: '2024-05-06',
    //   },
    ],
    // 以下是弹窗：0出现1关闭
    // 1基本信息，2分类添加，3商品添加，4分类选择
    pop1: 1, pop2: 1, pop3: 1, pop4: 1,
    popCateName: '', //弹窗分类名
    popGname: '', //弹窗商品名
    popDesc: '', //弹窗商品描述
    popPrice: '', //弹窗商品价格
    popNum: '', //商品数量
    popGimg: '', //商品图片
    popCateid: 0, //商品分类id
    popCode: '', //商品码选择
    popGid: 0, //弹窗商品ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ code: options.code });
    this.getOne(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 返回
  toBack: function (e) {
    console.log(e);
    wx.navigateBack({
      delta: 1
    }); return
  },

  // 获取信息
  getOne: function (e) {
    var that = this;
    wx.request({
        method: 'POST',
        url: app.globalData.domainXcx + '/shop/one',
        data: {id: e},
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code < 0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            var d = res.data;
            console.log(d);
            that.setData({
                id: d.id,
                shopName: d.title,
                desc: d.describe,
                bgimg: d.bgimg,
                headimg: d.headimg,
                adimg: d.adimg,
                cateTotal: d.cateTotal,
                catelist: d.cateList,
                gTotal: d.goodsTotal,
                glist: d.goodsList,
                orderTotal: d.orderTotal,
                orderlist: d.orderList,
                commentTotal: d.commentTotal,
                commentlist: d.commentList,
                followTotal: d.followTotal,
                followlist: d.followList,
                showCode: d.showCode,
                visitNum: d.visitNum,
                useNum: d.useNum,
            });
        },
        fail: function () {
            console.log('error');
        }
    });
  },

  // 弹窗
  popShow: function (e) {
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
        this.setData({ pop1: 0 });
    } else if (type == 2) {
        this.setData({ pop2: 0 });
    } else if (type == 3) {
        this.setData({ pop3: 0 });
    } else if (type == 4) {
        var gid = e.currentTarget.dataset.gid;
        this.setData({ pop4: 0, popGid: gid, });
    } else {
        wx.showToast({
            title: '弹窗错误', icon: 'none'
        }); return
    }
  },

  // 关闭弹窗
  popClose: function (e) {
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
        this.setData({ pop1: 1 });
    } else if (type == 2) {
        this.setData({ pop2: 1 });
    } else if (type == 3) {
        this.setData({ pop3: 1 });
    } else if (type == 4) {
        this.setData({ pop4: 1, popGid: 0, });
    } else {
        wx.showToast({
            title: '弹窗错误', icon: 'none'
        }); return
    }
  },

  // 店名
  toShopName: function (e) {
    this.setData({
        shopName: e.detail.value,
    });
  },

  // 描述
  toDesc: function (e) {
    this.setData({
        desc: e.detail.value,
    });
  },

  // 保存信息
  saveInfo: function (e) {
      var that = this;
    var formData = {
        id: this.data.id,
        shopName: this.data.shopName,
        describe: this.data.desc,
    };
    console.log(formData); //return
    wx.request({
        method: 'POST',
        url: app.globalData.domainXcx + '/shop/modify',
        data: formData,
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code!=0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            wx.showToast({
              title: '修改成功', icon: 'none'
            });
            that.viewReload();
        },
        fail: function () {
            console.log('error');
        }
    });
  },

  // 刷新页面
  viewReload: function (e) {
    var param = '?id=' + this.data.id;
    wx.navigateTo({
        url: '/pages/index/shop/index' + param,
    }); 
  },

  // 选择背景图片
  uploadBg: function (e) {
    wx.showLoading({
        title: '正在处理图片...',
    });
    wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
            // 获取文件路径
            const filePath = res.tempFilePaths[0];
            console.log(filePath);
            // 读取文件
            wx.getFileSystemManager().readFile({
                filePath: filePath,
                encoding: 'base64',
                success: res => {
                    // 将文件内容转换为base64字符串
                    const base64Data = 'data:image/png;base64,' + res.data;
                    // 可以在这里使用base64字符串
                    console.log(base64Data);
                    this.setData({
                        head: base64Data,
                    });
                    var imgAry = {
                        link: base64Data,
                        type: 'bg',
                    };
                    this.upload(imgAry);
                },
                fail: err => {
                    console.error('读取文件失败', err);
                    wx.showToast({
                      title: '读取文件失败', icon: 'none'
                    }); return
                }
            });
        },
        fail: err => {
            console.error('选择图片失败', err);
            wx.showToast({
              title: '选择图片失败', icon: 'none'
            }); return
        }
    });
  },

  // 选择头像图片
  uploadHead: function (e) {
    wx.showLoading({
        title: '正在处理图片...',
    });
    wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
            // 获取文件路径
            const filePath = res.tempFilePaths[0];
            console.log(filePath);
            // 读取文件
            wx.getFileSystemManager().readFile({
                filePath: filePath,
                encoding: 'base64',
                success: res => {
                    // 将文件内容转换为base64字符串
                    const base64Data = 'data:image/png;base64,' + res.data;
                    // 可以在这里使用base64字符串
                    console.log(base64Data);
                    this.setData({
                        head: base64Data,
                    });
                    var imgAry = {
                        link: base64Data,
                        type: 'head',
                    };
                    this.upload(imgAry);
                },
                fail: err => {
                    console.error('读取文件失败', err);
                    wx.showToast({
                      title: '读取文件失败', icon: 'none'
                    }); return
                }
            });
        },
        fail: err => {
            console.error('选择图片失败', err);
            wx.showToast({
              title: '选择图片失败', icon: 'none'
            }); return
        }
    });
  },

  // 选择广告图片
  uploadAdd: function (e) {
    wx.showLoading({
        title: '正在处理图片...',
    });
    wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
            // 获取文件路径
            const filePath = res.tempFilePaths[0];
            console.log(filePath);
            // 读取文件
            wx.getFileSystemManager().readFile({
                filePath: filePath,
                encoding: 'base64',
                success: res => {
                    // 将文件内容转换为base64字符串
                    const base64Data = 'data:image/png;base64,' + res.data;
                    // 可以在这里使用base64字符串
                    console.log(base64Data);
                    this.setData({
                        ad: base64Data,
                    });
                    var imgAry = {
                        link: base64Data,
                        type: 'ad',
                    };
                    this.upload(imgAry);
                },
                fail: err => {
                    console.error('读取文件失败', err);
                    wx.showToast({
                      title: '读取文件失败', icon: 'none'
                    }); return
                }
            });
        },
        fail: err => {
            console.error('选择图片失败', err);
            wx.showToast({
              title: '选择图片失败', icon: 'none'
            }); return
        }
    });
  },

  // 上传图片
  upload: function (e) {
    console.log(e);
    var that = this;
    var httpUrl = app.globalData.domainXcx + '/shop/upload/';
    if (e.type == 'bg') {
        httpUrl += 'bg';
    } else if (e.type == 'head') {
        httpUrl += 'head';
    } else {
        httpUrl += 'ad';
    }
    wx.request({
        method: 'POST',
        url: httpUrl,
        data: {id: this.data.id, base64: e.link},
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code!=0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            wx.showToast({
              title: '上传成功', icon: 'none'
            });
            that.viewReload();
        },
        fail: function () {
            console.log('error');
        }
    });
  },

  // 弹窗分类名
  toPopCateName: function (e) {
    this.setData({
        popCateName: e.detail.value,
    });
  },

  // 保存分类
  saveCate: function (e) {
    var that = this;
    var formData = {
        id: this.data.id,
        cateName: this.data.popCateName,
    };
    console.log(formData); //return
    wx.request({
        method: 'POST',
        url: app.globalData.domainXcx + '/shop/cate/add',
        data: formData,
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code!=0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            wx.showToast({
              title: '添加成功', icon: 'none'
            });
            that.viewReload();
        },
        fail: function () {
            console.log('error');
        }
    });
  },

  // 商品名称
  popGname: function (e) {
    this.setData({
        popGname: e.detail.value,
    });
  },

  // 商品描述
  popDesc: function (e) {
    this.setData({
        popDesc: e.detail.value,
    });
  },

  // 商品价格
  popPrice: function (e) {
    this.setData({
        popPrice: e.detail.value,
    });
  },

  // 商品数量
  popNum: function (e) {
    this.setData({
        popNum: e.detail.value,
    });
  },

  // 商品图片上传
  popGimg: function (e) {
    // wx.showLoading({
    //     title: '正在处理图片...',
    // });
    wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
            // 获取文件路径
            const filePath = res.tempFilePaths[0];
            console.log(filePath);
            // 读取文件
            wx.getFileSystemManager().readFile({
                filePath: filePath,
                encoding: 'base64',
                success: res => {
                    // 将文件内容转换为base64字符串
                    const base64Data = 'data:image/png;base64,' + res.data;
                    // 可以在这里使用base64字符串
                    console.log(base64Data);
                    this.setData({
                        popGimg: base64Data,
                    });
                },
                fail: err => {
                    console.error('读取文件失败', err);
                    wx.showToast({
                      title: '读取文件失败', icon: 'none'
                    }); return
                }
            });
        },
        fail: err => {
            console.error('选择图片失败', err);
            wx.showToast({
              title: '选择图片失败', icon: 'none'
            }); return
        }
    });
  },

  // 保存商品
  saveGoods: function (e) {
    var that = this;
    var formData = {
        // code: this.data.code,
        shopid: this.data.id,
        gname: this.data.popGname,
        gdesc: this.data.popDesc,
        gprice: this.data.popPrice,
        gnum: this.data.popNum,
        gimg: this.data.popGimg,
    };
    if (formData.gname == '') {
        wx.showToast({
          title: '商品名必填', icon: 'none'
        }); return
    }
    if (formData.gprice == '') {
        wx.showToast({
          title: '商品价格必填', icon: 'none'
        }); return
    }
    if (formData.gnum == '') {
        wx.showToast({
          title: '商品数量必填', icon: 'none'
        }); return
    }
    console.log(formData); //return
    wx.request({
        method: 'POST',
        url: app.globalData.domainXcx + '/shop/goods/add',
        data: formData,
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code!=0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            wx.showToast({
              title: '添加成功', icon: 'none'
            });
            that.viewReload();
        },
        fail: function () {
            console.log('error');
        }
    });
  },

  // 设置分类
  setCate: function (e) {
    console.log(e);
    var that = this;
    var cateid = e.currentTarget.dataset.cateid;
    var formData = {
        // shopid: this.data.id,
        gid: this.data.popGid,
        cateid: cateid,
    };
    if (formData.gid == 0) {
        wx.showToast({
          title: '商品必须', icon: 'none'
        }); return
    }
    if (formData.cateid == 0) {
        wx.showToast({
          title: '分类必须', icon: 'none'
        }); return
    }
    console.log(formData); //return
    wx.request({
        method: 'POST',
        url: app.globalData.domainXcx + '/shop/goods/cate/modify',
        data: formData,
        timeout: 10000, //接口超时10S
        success: function (res) {
            res = res.data;
            console.log(res);
            if (res.code!=0) {
                wx.showToast({
                    title: res.msg, icon: 'none'
                }); return
            }
            wx.showToast({
              title: '设置成功', icon: 'none'
            });
            that.viewReload();
        },
        fail: function () {
            console.log('error');
        }
    });
  },
})